package org.myy.learn.hot.finish.普通数组;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class 合并区间 {
    public int[][] merge(int[][] intervals) {
        int n = intervals.length;
        //0行2列的空数组
        if(n == 0){return new int[0][2];}
        //排序
        Arrays.sort(intervals, Comparator.comparingInt((int[] a) -> a[0]));
        //Arrays.sort(intervals, Comparator.comparing(e -> e[0]));    //ToDo  单元素
        List<int[]> merges = new ArrayList<>();//List集合，操作方便          ToDo 为什么是int[]
        for (int i = 0; i<n; i++){
            int L = intervals[i][0], R = intervals[i][1];
            if (merges.size() == 0 || merges.get(merges.size() - 1)[1] < L){
                merges.add(new int[]{L, R});
            } else {
                merges.get(merges.size() - 1)[1] = Math.max(R, merges.get(merges.size() - 1)[1]);
            }
        }
        return merges.toArray(new int[merges.size()][]);
    }
}
